package com.wbase.permission.helper

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.PermissionChecker
import androidx.fragment.app.FragmentActivity
import com.wbase.base.app.App
import com.wbase.base.logger.Logger
import com.wbase.permission.request.Permission

abstract class AbsPermissionHelper {

    protected abstract fun getTag(): String

    protected fun isSdkUp23(): Boolean {
        return Build.VERSION.SDK_INT >= 23
    }

    fun hasPermission(permission: String): Boolean {
        var hasPermission = true
        //6.0或者以后
        if (isSdkUp23()) {
            hasPermission = PermissionChecker.checkSelfPermission(App.getContext(), permission) == PermissionChecker.PERMISSION_GRANTED
            Logger.i(getTag(), ">=23 hasPermission = $hasPermission")
        }
        return hasPermission
    }

    private fun isNotAskChecked(activity: FragmentActivity, permission: String): Boolean{
        return !ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
    }

    fun getDeniedPermissionList(activity: AppCompatActivity, requestList: ArrayList<String>): ArrayList<String>{
        val deniedList = ArrayList<String>()

        if (isSdkUp23()) {
            requestList.forEach {
                if(!hasPermission(it)){
                    deniedList.add(it)
                }
            }
        }

        return deniedList
    }

    protected fun onAllPermissionGranted(
        requestList: ArrayList<String>,
        callback: (isAllGranted: Boolean,
                   isAllCantShow: Boolean,
                   deniedList: ArrayList<String>,
                   list: ArrayList<Permission>) -> Unit) {
        val allGranted = true
        val allCantShow = false

        val resultList = ArrayList<Permission>()
        requestList.forEach {
            resultList.add(
                Permission(
                    it,
                    true,
                    true
                )
            )
        }

        callback(allGranted, allCantShow, ArrayList(), resultList)
    }
}